<?php

namespace app\index\dao;

use app\common\model\LawCase;
use app\common\model\Trade;
use app\index\dao\traits\UidTrait;
use ShidianUtil\Concurrent\Synchronizer;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use think\Collection;

/**
 * LawCaseDao 数据访问对象
 * Class LawCaseDao
 * @package app\dao
 * @method LawCase findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method LawCase insertActive(array $params, array $allow_field = [])
 * @method LawCase updateActive(LawCase $model, array $params, array $allow_field = [])
 * @method LawCase findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method LawCase updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(LawCase $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class LawCaseDao
{
    use DaoTrait;
    use UidTrait;

    /**
     * @var \app\common\model\LawCase
     */
    private $baseModel;

    /**
     * LawCaseDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = LawCase::class;
    }

    /**
     * 插入案源
     * @param $params
     * @return LawCase
     */
    public function insertLawCase($params): LawCase
    {
        $record = null;

        $signature = __CLASS__;
        $this->getSynchronizer()->synchronized($signature, function () use ($params, &$record) {

            if (is_blank($params['uid'] ?? null)) {
                $params['uid'] = $this->getUid(2);
            }

            $record = $this->insertActive($params);
        });

        if (!$record) {
            throw new \RuntimeException('保存失败，请稍后再试');
        }

        return $record;
    }

    // 律师端-可抢购案源列表
    public function selectCanRush($cityId, $categoryId, $kw, $page, $page_size): Collection
    {
        return LawCase::when(is_id($cityId), fn($query) => $query->where('cityId', $cityId))
            ->when(is_id($categoryId), fn($query) => $query->where('categoryId', $categoryId))
            ->where('isPublish', '1')
            ->where('publishTime', '<=', time())
            ->where('surplus', '>', 0)
            ->where('status', '<>', 2)
            ->search('ask', $kw)
            ->with([
                'province' => fn($query) => $query->shortArea(),
                'city' => fn($query) => $query->shortArea(),
            ])
            ->order('id', 'DESC')
            ->paging($page, $page_size)
            ->select();
    }

    // 律师端-已抢购案源列表
    public function selectRushed($lawyerId, $cityId, $categoryId, $kw, $page, $page_size)
    {
        $tableName = LawCase::getTable();

        return LawCase::leftJoin('trade t', "$tableName.id=t.lawCaseId and t.memberId=:memberId and t.tradeType=:tradeType", ['memberId' => $lawyerId, 'tradeType' => TRADE_LAS_CASE])
            ->where('t.memberId', $lawyerId)
            ->where('t.tradeType', TRADE_LAS_CASE)
            ->where('t.payStatus', Trade::PAID)
            ->where('t.refundStatus', Trade::NOTREFUND)
            ->when(is_id($cityId), fn($query) => $query->where('cityId', $cityId))
            ->when(is_id($categoryId), fn($query) => $query->where('categoryId', $categoryId))
            ->search('ask', $kw)
            ->tableField(true, $tableName)
            ->with([
                'province' => fn($query) => $query->shortArea(),
                'city' => fn($query) => $query->shortArea(),
            ])
            ->withSum([
                'trades' => fn($query) => $query->where('memberId', $lawyerId)
                    ->where('tradeType', TRADE_LAS_CASE)
                    ->where('payStatus', Trade::PAID)
                    ->where('refundStatus', Trade::NOTREFUND)
            ], 'num')
            ->order('t.id', 'DESC')
            ->paging($page, $page_size)
            ->select();
    }

    public function findDetail($id): ?LawCase
    {
        return LawCase::where('id', $id)
            ->with([
                'category' => fn($query) => $query->field(['id', 'name']),
                'days' => fn($query) => $query->field(['id', 'name']),
                'money' => fn($query) => $query->field(['id', 'name']),
                'province' => fn($query) => $query->shortArea(),
                'city' => fn($query) => $query->shortArea(),
            ])
            ->find();
    }

    private function getSynchronizer(): Synchronizer
    {
        return app(Synchronizer::class);
    }
}
